<template>
  <div id="mapContainer" style="width: 100%; height: 100%;"></div>
</template>

<script>
export default {
  data() {
    return {
      map: null,
      geocoder: null,
      markers: [],
      clusters: null
    };
  },
  async mounted() {
    // 等待 AMap API 加载完成
    await this.loadAMapScript();
    this.initializeMap();
  },
  methods: {
    loadAMapScript() {
      return new Promise((resolve, reject) => {
        if (window.AMap) {
          resolve();
          return;
        }
        const script = document.createElement('script');
        script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=YOUR_AMAP_KEY';
        script.onload = resolve;
        script.onerror = reject;
        document.head.appendChild(script);
      });
    },

    initializeMap() {
      // 初始化地图
      this.map = new AMap.Map('mapContainer', {
        zoom: 10, // 初始缩放级别
        center: [116.397428, 39.90923] // 初始中心点
      });

      // 初始化地理编码服务
      this.geocoder = new AMap.Geocoder();

      // 获取设备数据
      this.fetchEquipmentData().then(equipmentData => {
        const validData = this.filterInvalidCoordinates(equipmentData);
        this.processCoordinates(validData);
      });
    },

    async fetchEquipmentData() {
      // 模拟从 API 获取设备数据
      return [
        { lat: 39.90923, lng: 116.397428 },
        { lat: 38.977737, lng: 122.338802 },
        // 添加更多数据
      ];
    },

    filterInvalidCoordinates(data) {
      return data.filter(point => 
        point.lat >= -90 && point.lat <= 90 &&
        point.lng >= -180 && point.lng <= 180
      );
    },

    async processCoordinates(data) {
      const markers = [];
      const locationPromises = data.map(async (point) => {
        try {
          const result = await this.getLocation(point);
          if (result) {
            const marker = new AMap.Marker({
              position: [point.lng, point.lat],
              map: this.map,
              title: result
            });
            markers.push(marker);
          }
        } catch (error) {
          console.error(`Error fetching address for point (${point.lng}, ${point.lat}):`, error);
        }
      });
      await Promise.all(locationPromises);
      this.addCluster(markers);
    },

    getLocation(point) {
      return new Promise((resolve, reject) => {
        this.geocoder.getAddress([point.lng, point.lat], (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            const address = result.regeocode.formattedAddress || 'Unknown';
            resolve(address);
          } else {
            reject(new Error('Geocoding failed'));
          }
        });
      });
    },

    addCluster(markers) {
      if (this.clusters) {
        this.clusters.clearMarkers();
      }
      this.clusters = new AMap.MarkerClusterer(this.map, markers, {
        // 可选配置
        gridSize: 80,
        maxZoom: 15
      });
    }
  }
};
</script>

<style>
#mapContainer {
  width: 100%;
  height: 100%;
}
</style>
